#include "Bhattacharyya.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "def.h"
#include "nrio.h"
#include "nrarith.h"
#include "nralloc.h"

/*
 *
 *
 *	Ouvre les fichiers texte contenant les histogrammes de 2 images.
 *
 *
 *
 */


int main(int argc, char *argv[])
{
	FILE *f_rice, *f_cubes;
	char ligne_rice[10], ligne_cubes[10];
	int toto_rice[255], toto_cubes[255];
	int i, j;
	char filename1[100], filename2[100], filename3[100];
	float coefBhatta, distBhatta;
	
	for(i=0;i<255;i++)
	{
		toto_rice[i]=0;
		toto_cubes[i]=0;
	}
	sprintf(filename1, "%s",argv[1]);
	sprintf(filename2, "%s",argv[2]);
	sprintf(filename3, "%s",argv[3]);

	f_rice=fopen(filename1, "r");
	f_cubes=fopen(filename2, "r");
	printf("Fichiers ouverts.\n");
	
	if (f_rice != NULL && f_cubes != NULL)
   {
   	for(i=0; i<255; i++)	
		{
			fgets(ligne_rice, 10, f_rice);
			toto_rice[i]=atoi(ligne_rice);
//			printf("lignerice %s, totorice %d\n", ligne_rice, toto_rice[i]);
			fgets(ligne_cubes, 10, f_cubes);
			toto_cubes[i] = atoi(ligne_cubes);
//			printf("lignecubes %s, totocubes %d\n", ligne_cubes, toto_cubes[i]);
		}

for(i=0;i<255;i++)
		printf("rice : %d ", toto_rice[i]);

		printf("\ncubes : %s", toto_cubes);

		printf("\npouet go bhatta.\n");
		coefBhatta = coef_Bhatta(toto_rice, toto_cubes);
		printf("Coef Bhatta = %f\n", coefBhatta);
		
		distBhatta = dist_Bhatta(coefBhatta);
		printf("Distance de Bhatta : %f\n", distBhatta);

		printf("Fermeture fichiers...\n");
		fclose(f_rice);
		fclose(f_cubes);
		printf("Fichiers fermés.\n");
		
		FILE *f=fopen(filename3, "a");
		fprintf(f, "%f\n", distBhatta);
		fclose(f);

		
   }
   else	printf("Impossible d'ouvrir un fichier.\n");

	return 1;
}

float coef_Bhatta(int *image1, int *image2)
{
	int i;
	float Bhatta=0;
	for(i=0 ; i<255 ; i++)
	{
		Bhatta += sqrt(image1[i] * image2[i]);
		printf("bhatta %f.\n", Bhatta);
	}
	return Bhatta;
}

float dist_Bhatta(int Bhatta)
{
	float Distance = 0;
	Distance = -(log(Bhatta));
	return Distance;
}
